// ===============================================
// marquee
// 
// Create by Will on 2020/10/26 8:29 PM
// Copyright @data_food.All rights reserved.
// ===============================================

import 'package:flutter/widgets.dart';

class Marquee extends StatefulWidget {
  final Widget child;
  final Axis direction;
  final Duration animationDuration, pauseDuration;

  Marquee({
    @required this.child,
    this.direction: Axis.horizontal,
    this.animationDuration: const Duration(seconds: 3),
    this.pauseDuration: const Duration(seconds: 1),
  });

  @override
  _MarqueeState createState() => _MarqueeState();
}

class _MarqueeState extends State<Marquee> {
  ScrollController scrollController;

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    WidgetsBinding.instance.addPostFrameCallback(scroll);
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: widget.direction,
      controller: scrollController,
      child: widget.child,
    );
  }

  void scroll(_) async {
    while (scrollController.hasClients) {
      await Future.delayed(widget.pauseDuration);
      if (scrollController.hasClients)
        await scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: widget.animationDuration,
          curve: Curves.ease,
        );
      await Future.delayed(widget.pauseDuration);
      if (scrollController.hasClients) await scrollController.jumpTo(0);
    }
  }
}
